import { useState, useCallback } from 'react';
import { ChineseInputHandler } from '../utils/chineseInput';

export function useInputHandler(initialValue: string = '') {
  const [value, setValue] = useState(initialValue);
  const [cursorPosition, setCursorPosition] = useState(0);
  const [history, setHistory] = useState<string[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);

  const insertText = useCallback((text: string) => {
    const newValue = ChineseInputHandler.insertAtPosition(value, cursorPosition, text);
    setValue(newValue);
    setCursorPosition(cursorPosition + Array.from(text).length);
  }, [value, cursorPosition]);

  const deleteText = useCallback(() => {
    if (cursorPosition > 0) {
      const newValue = ChineseInputHandler.deleteAtPosition(value, cursorPosition);
      setValue(newValue);
      setCursorPosition(cursorPosition - 1);
    }
  }, [value, cursorPosition]);

  const moveCursor = useCallback((direction: 'left' | 'right' | 'home' | 'end') => {
    const maxPosition = Array.from(value).length;
    
    switch (direction) {
      case 'left':
        setCursorPosition(Math.max(0, cursorPosition - 1));
        break;
      case 'right':
        setCursorPosition(Math.min(maxPosition, cursorPosition + 1));
        break;
      case 'home':
        setCursorPosition(0);
        break;
      case 'end':
        setCursorPosition(maxPosition);
        break;
    }
  }, [value, cursorPosition]);

  const navigateHistory = useCallback((direction: 'up' | 'down') => {
    if (direction === 'up' && history.length > 0) {
      const newIndex = Math.min(historyIndex + 1, history.length - 1);
      setHistoryIndex(newIndex);
      const historyValue = history[newIndex];
      setValue(historyValue);
      setCursorPosition(Array.from(historyValue).length);
    } else if (direction === 'down' && historyIndex >= 0) {
      const newIndex = historyIndex - 1;
      if (newIndex >= 0) {
        setHistoryIndex(newIndex);
        const historyValue = history[newIndex];
        setValue(historyValue);
        setCursorPosition(Array.from(historyValue).length);
      } else {
        setHistoryIndex(-1);
        setValue('');
        setCursorPosition(0);
      }
    }
  }, [history, historyIndex]);

  const submitValue = useCallback(() => {
    if (value.trim()) {
      setHistory(prev => [value, ...prev.slice(0, 49)]); // 保留50条历史
      setHistoryIndex(-1);
      const submittedValue = value;
      setValue('');
      setCursorPosition(0);
      return submittedValue;
    }
    return null;
  }, [value]);

  const clearValue = useCallback(() => {
    setValue('');
    setCursorPosition(0);
  }, []);

  return {
    value,
    cursorPosition,
    history,
    historyIndex,
    actions: {
      insertText,
      deleteText,
      moveCursor,
      navigateHistory,
      submitValue,
      clearValue,
      setValue,
      setCursorPosition
    }
  };
}